package com.xinpu.service;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/**
 * 用户登录token 管理
 */
@Service
public class TokenService {

    private static Logger logger = LoggerFactory.getLogger(TokenService.class);


    //过期时间为15天
    public static final int EXPIRE_TIME = 15 * 24 * 60 * 60 * 1000;

    /**
     * 密钥
     */
    private static final String SECRET = "WJKLFDKJSKJFKJDAKFJKJKKFDIFUU*(DU*FJKDFDHFDJI*(^%%^%^%989909090proxy";

    private static final String TOKEN_KEY = "token";

    /**
     * 生成token
     *
     * @param map 需要生成的 map
     * @return
     */
    public TokenResult generate(Map<String, String> map) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);

            JWTCreator.Builder builder = JWT.create();
            Iterator names = map.keySet().iterator();
            while (names.hasNext()) {
                String name = (String) names.next();
                if (name != null) {
                    String value = map.get(name);
                    builder.withClaim(name, value);
                }
            }
            builder.withExpiresAt(date);
            String token = builder.sign(algorithm);
            return new TokenResult(token, date);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }

    }

    /**
     * 获取内容
     *
     * @param key
     * @return
     */
    public String getItem(String token, String key) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim(key).asString();
    }

    /**
     * 验证token是否合法
     *
     * @param token
     * @return
     */
    public boolean valid(String token) {
        try {
            DecodedJWT decode = JWT.decode(token);
            Date date = decode.getExpiresAt();
            if ((new Date()).getTime() > date.getTime()) {
                logger.error("token已经过期");
                return false;
            }
            return true;
        } catch (Exception ex) {
            return false;
        }
    }


    /**
     * token 返回内容
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class TokenResult {
        /**
         * token
         */
        private String token;
        /**
         * 过期时间戳
         */
        private Date expire;
    }

}
